package io.renren.modules.api.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileWriter;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.Wrapper;
import io.renren.common.exception.RRException;
import io.renren.common.utils.FileConstant;
import io.renren.common.utils.FileUtils;
import io.renren.common.validator.Assert;
import io.renren.modules.sys.dao.SysLogDao;
import io.renren.modules.sys.entity.SysLogEntity;
import io.renren.modules.sys.shiro.ShiroUtils;
import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.api.dao.WeixinNoDao;
import io.renren.modules.api.entity.WeixinNoEntity;
import io.renren.modules.api.service.WeixinNoService;


@Service("weixinNoService")
public class WeixinNoServiceImpl extends ServiceImpl<WeixinNoDao, WeixinNoEntity> implements WeixinNoService {

    @Value("${htmlbak.path}")
    private String htmlbakPath;

    @Autowired
    private SysLogDao sysLogDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        String name = (String)params.get("name");
        String dnsid = (String)params.get("dnsid");

        Wrapper<WeixinNoEntity> entityWrapper=new EntityWrapper<WeixinNoEntity>()
                .like(StringUtils.isNotBlank(name),"wxno", name)
                .or().like(StringUtils.isNotBlank(name),"picture", name)
                .or().like(StringUtils.isNotBlank(name),"url", name)
                .or().like(StringUtils.isNotBlank(name),"linkurl", name)
                .or().like(StringUtils.isNotBlank(name),"dnsname", name)
                .or().like(StringUtils.isNotBlank(name),"remark", name)
                .or().like(StringUtils.isNotBlank(name),"allurl", name);

        if(StringUtils.isNotBlank(dnsid)){
            entityWrapper.and().eq(StringUtils.isNotBlank(dnsid),"dnsid",dnsid);
        }

        Page<WeixinNoEntity> page = this.selectPage(
                new Query<WeixinNoEntity>(params).getPage(),entityWrapper
        );

        // 处理访问链接
        List<WeixinNoEntity> list=page.getRecords();
        /*for(int i=0;i<list.size();i++){
            String linkUrl=list.get(i).getUrl()+list.get(i).getLinkurl();
            list.get(i).setLinkurl(linkUrl);
        }*/
        page.setRecords(list);

        return new PageUtils(page);
    }

    @Override
    public void updateWxnoAndImage(WeixinNoEntity weixinNo) throws Exception {

        Assert.isBlank(weixinNo.getPath(),"路径不能为空");
        // 根据id查询原始数据 比对是否一样 如果不一样则修改服务器文件
        WeixinNoEntity wxnoOld=this.selectById(weixinNo.getId());
        String path=weixinNo.getPath()+weixinNo.getLinkurl();//绝对路径
        String wxno=weixinNo.getWxno();
        String image=weixinNo.getPicture();
        // 读取文件字符串
        String html= FileUtils.getHtmlByFile(path);
        // 判断如何可以修改微信号或图片地址 则备份文件
        if(!StrUtil.equals(wxno,wxnoOld.getWxno())||!StrUtil.equals(image,wxnoOld.getPicture())){

            //生成备份文件路径
            Date d = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String dateNowStr = sdf.format(d);
            String mbFile=htmlbakPath+dateNowStr+"/"+new Date().getTime()+FileUtils.getFileName(path); //目标路径

            // 备份记录日志
            SysLogEntity syslog=new SysLogEntity();
            syslog.setCreateDate(new Date());
            syslog.setTime(new Long(weixinNo.getId()));                     //微信链接的ID
            syslog.setOperation("备份html");                                 //操作名
            syslog.setParams(JSONObject.toJSONString(weixinNo));            //参数
            syslog.setMethod(mbFile);                                       //备份文件路径
            syslog.setUsername(ShiroUtils.getUserEntity().getUsername());   //操作人
            sysLogDao.insert(syslog);

            FileUtil.copy(path,mbFile,true); //备份

            // 修改文字微信号
            // 检查是否有对应的模版
            Document doc= Jsoup.parse(html);
            Element elements_no=doc.select(FileConstant.WXNO_MODEL_NO).first();

            // 如果传入的微信号 与原来不一样则修改
            if(!StrUtil.equals(wxno,wxnoOld.getWxno())){

                //如果传入了旧微信号 则创建模版，模版创建分两种方式  一种是纯文字 一种是文字图片结合的
                if(StringUtils.isNotBlank(weixinNo.getOldwxno())){
                    String oldwxno=weixinNo.getOldwxno();
                    String body=doc.html();

                    if(body.indexOf(oldwxno)==-1){
                        throw new RRException("旧微信号不存在，请确认后重新输入");
                    }

                    //判断是否是纯文字
                    if(body.indexOf("\""+oldwxno+"\"")!=-1){

                        //替换图片
                        body=ReUtil.replaceAll(body,"src=\"image/"+oldwxno+".png\"","model-id=\"wxno_hx_image\"");
                        body=ReUtil.replaceAll(body,"src=\"images/"+oldwxno+".png\"","model-id=\"wxno_hx_image\"");
                        body=ReUtil.replaceAll(body,"src=\"image/"+oldwxno+".jpg\"","model-id=\"wxno_hx_image\"");
                        body=ReUtil.replaceAll(body,"src=\"images/"+oldwxno+".jpg\"","model-id=\"wxno_hx_image\"");

                        //图片替换完了，再替换文字
                        body= ReUtil.replaceAll(body,"\""+oldwxno+"\"","$(\"#wxno_model_no\").html()");
                        body=ReUtil.replaceAll(body,oldwxno,"<wxno class=\"wxno_hx_no\"></wxno>");

                        doc.html(body);
                        setCommonDocHtml(doc,weixinNo); //设置公有参数

                    }else{
                        //文字图片结合

                        //替换图片
                        body=ReUtil.replaceAll(body,"src=\"image/"+oldwxno+".png\"","model-id=\"wxno_hx_image\"");
                        body=ReUtil.replaceAll(body,"src=\"images/"+oldwxno+".png\"","model-id=\"wxno_hx_image\"");
                        body=ReUtil.replaceAll(body,"src=\"image/"+oldwxno+".jpg\"","model-id=\"wxno_hx_image\"");
                        body=ReUtil.replaceAll(body,"src=\"images/"+oldwxno+".jpg\"","model-id=\"wxno_hx_image\"");

                        //图片替换完了，再替换文字
                        body=ReUtil.replaceAll(body,">"+oldwxno+"<","><wxno class=\"wxno_hx_no\"></wxno><");
                        body=ReUtil.replaceAll(body,oldwxno,"<wxno class=\"wxno_hx_no\"></wxno>");

                        doc.html(body);
                        setCommonDocHtml(doc,weixinNo); //设置公有参数

                    }
                }else{
                    Assert.isNull(elements_no,"微信号模版不存在");
                    doc.select(FileConstant.WXNO_MODEL_NO).first().html(wxno);
                }
            }
            // 修改图片地址
            Element elements_images=doc.select(FileConstant.WXNO_MODEL_IMAGE).first();

            if(!StrUtil.equals(image,wxnoOld.getPicture())){
                // Assert.isNull(elements_images,"微信图片模版不存在");
                if(elements_images!=null){
                    doc.select(FileConstant.WXNO_MODEL_IMAGE).first().html(image);
                }
            }

            FileWriter writer = new FileWriter(path);
            writer.write(doc.html());
        }
    }


    /**
     * 设置公有参数 （自动加载微信号的模版）
     */
    public static void setCommonDocHtml(Document doc,WeixinNoEntity weixinNo){

        // 变量
        doc.append("<div style=\"display: none\" id=\"wxno_model_no\">"+weixinNo.getWxno()+"</div>")
           .append("<div id=\"wxno_model_image\" style=\"display: none\">"+weixinNo.getPicture()+"</div>");

        //javascript 自动化加载数据
        doc.append("<script>\n" +
                        "    $(function(){\n" +
                        "        var no=$(\"#wxno_model_no\").html();\n" +
                        "        var image=$(\"#wxno_model_image\").html();\n" +
                        "        $(\".wxno_hx_no\").each(function(){\n" +
                        "            $(this).html(no);\n" +
                        "        })\n" +
                        "        $('*[model-id=\"wxno_hx_image\"]').each(function(){\n" +
                        "            $(this).attr(\"src\",image);\n" +
                        "        })\n" +
                        "    })\n" +
                        "  </script>");
    }
}
